$(document).ready(function () {

    var dataStr = deepClone(localStorage.getItem("templeteReviewData"));
    localStorage.removeItem("templeteReviewData");
    var data = JSON.parse(dataStr);
    var btn = '<div class="form-group"><div class="col-sm-12 text-center"><button class="btn btn-primary buttonColor btnSize" type="button" id="btnQuery">查询</button><button class="btn btn-primary buttonColor btnSize" type="button" id="resetBtn">重置</button></div></div>';
    var formElement = '';
    //列表集合
    var columns = [{
        checkbox: true
    }];
    //查询条件集合
    var conditions = data.baseCommonqueryconditions;
    //列表展示集合
    var results = data.baseCommonqueryresults;
    //表头数据
    var head = data.baseCommonquery;
    //sql脚本
    var sql = '';
    var myParams = {
        results: JSON.stringify(results),
        condition: JSON.stringify(conditions)
    };
    if (head) {
        sql = head.SQLSCRIPT;
        myParams.sql = head.SQLSCRIPT;
    }
    if (results) {
        for (var i = 0; i < results.length; i++) {
            var resultItem = results[i];
            columns.push({
                    field: 'field' + i,
                    halign: 'center',
                    title: resultItem.NAME1
                }
            );
        }
    }

    //下拉框集合
    var selectComponentList = [];
    //日期框集合
    var dataComponentList = [];
    if (conditions) {
        var n = 1;
        for (var j = 0; j < conditions.length; j++) {
            var conditionItem = conditions[j];
            if (!$.trim(conditionItem.FIELDNAME)) {
                continue;
            }
            var itemVueModel = "myParams." + conditionItem.REPLACEFIELD;
            var itemName = conditionItem.REPLACEFIELD;
            var itemLabel = conditionItem.FIELDNAME;
            var required=conditionItem.ALLOWLANK=='1'?true:false;
            //如果是3的倍数则换行，既重新创建一个form—group
            if (j % 3 == 0) {
                n = 1;
                formElement += '<div class="form-group">'
            }
            //[{value: 1, text: "文本框"}, {value: 2, text: "区域文本框"}, {value: 3, text: "下拉框"}, {value: 4,text: "复选框"}, {value: 5, text: "日期型"}, {value: 6, text: "日期时间型"}, {value: 6, text: "数字编辑器"}]
            if (conditionItem.COMPONENTNAME == 1) {
                //输入框
                if(required){

                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><input type="text" name="' + itemName + '"v-model="' + itemVueModel + '" class="form-control" required/><span class="required">*</span></div></div>';
                }else {
                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><input type="text" name="' + itemName + '"v-model="' + itemVueModel + '" class="form-control" /></div></div>';
                }
            }
            if (conditionItem.COMPONENTNAME == 3) {
                //下拉框
                if(required){
                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><div class="input-group"><input type="text" name="' + itemName + '" :data-id="' + itemVueModel + '" id="' + itemName + '" class="form-control" required/><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div><span class="required2">*</span></div></div>';
                }else {

                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><div class="input-group"><input type="text" name="' + itemName + '" :data-id="' + itemVueModel + '" id="' + itemName + '" class="form-control" /><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div></div></div>';
                }
                selectComponentList.push({
                    id: itemName,
                    sql: conditionItem.INITVALUE
                });
            }
            if (conditionItem.COMPONENTNAME == 5) {
                //日期框
                if(required){
                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><input type="text" v-model="' + itemVueModel + '" name="' + itemName + '" id="' + itemName + '" class="form-control" required/><span class="required">*</span></div></div>';
                }else {
                    formElement += '<div class="col-sm-4"><label class="col-sm-4 control-label">' + itemLabel + '：</label><div class="col-sm-8"><input type="text" v-model="' + itemVueModel + '" name="' + itemName + '" id="' + itemName + '" class="form-control" /></div></div>';
                }
                dataComponentList.push({
                    id: itemName
                });
            }
            if (n % 3 == 0 || j == conditions.length - 1) {
                formElement += '</div>'
            }
            n++;

        }
    }
    $('#queryForm').append(formElement).append(btn);
    var queryConditions = new Vue({
        el: '#queryForm',
        data: {
            myParams: myParams
        }
    });

    for (var m = 0; m < selectComponentList.length; m++) {
        var selectComponentItem = selectComponentList[m];
        initSelecct(selectComponentItem.id, selectComponentItem.sql);
    }
    for (var k = 0; k < dataComponentList.length; k++) {
        var dataComponentItem = dataComponentList[k];
        initDate(dataComponentItem.id,dataComponentItem.id);
    }
    var me = $(this);
    var queryTime = 0;
    //存储主页面点击的行信息
    var curRow = {};

    /********************表格的初始化操作在此进行 ---- 实例化Grid ************************/
    var grid = $("#dataGrid").bootstrapTable({
        columns: columns,
        sortable: true,//是否可以排序，每一列都可以进行指定
        url: "../../../../api/baseCommonqueryController/selectAllDataByTempleteReview",//加载时调用的后台连接
        undefinedText: '',//字段值为undefine时显示的内容
        showRefresh: false,//是否显示刷新按钮
        showColumns: false,//是否显示列头
        striped: true,//是否显示表格线
        exportDataType: "all", //导出的数据类型
        exportTypes: ['excel'],//导出文件类型
        iconSize: "outline",//icon图标的显示方式
        toolbar: "#grdToolbar",//绑定表格的操作栏，就是新增、修改、删除按钮所在div的ID
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        },
        pagination: true,//是否分页
        clickToSelect: false,
        sidePagination: "server", // 表示分页时进行服务端请求
        method: 'post',//请求方法[post/get]
        dataField: 'data',
        pageNumber: 1,//页面分页的初始页码
        pageSize: 10,//每页显示数量(暂定每页10条，请暂勿修改，保持统一)
        pageList: [5, 10, 25, 50, 100],//每页显示的可选数量
        queryParamsType: "undefined",

        //查询参数配置
        queryParams: function (params) {
            var pIndex, myTotal;
            if (queryTime === 0) {
                pIndex = 1;
                myTotal = -1;
                queryTime++;
            }
            else {
                pIndex = params.pageNumber;
                myTotal = this.totalRows;
            }

            return {
                limit: params.pageSize,
                page: pIndex,
                allcount: myTotal,
                data: queryConditions.myParams,
                sortName: params.sortName,
                sortOrder: params.sortOrder
            }
        },

        //排序事件
        onSort: function (name, order) {
            grid.queryData();
        },
        onClickRow: function (row, $element) {
            curRow = row;
        },
        //数据加载完毕事件
        onLoadSuccess: function (result) {
            // 数据加载完成后处理某些信息

            //点击连接的时候弹出可编辑输入框，便于修改
            //基于控件：bootstrap-editable.js
            //参考博客地址:http://www.cnblogs.com/landeanfen/p/5821192.html
            $("#tableGrid a").click(function () {

            });
        }
    });

    /* 数据查询 */
    grid.queryData = function () {
        queryTime = 0;
        this.bootstrapTable('refresh', {
            silent: false
        });
    };

    /* 查询按钮点击 */
    $('#btnQuery').click(function () {
        if(!$("#queryForm").valid()){
            return;
        }
        grid.queryData();
    });

    /*重置按钮*/
    $('#resetBtn').click(function () {
        $('#queryForm').find("input")
            .not(':button, :submit, :reset, :hidden')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        myParams = {
            results: JSON.stringify(results),
            condition: JSON.stringify(conditions),
            sql: head.SQLSCRIPT
        }
        queryConditions.myParams = myParams;
    });
//深度克隆
    function deepClone(obj) {
        var result, oClass = isClass(obj);
        //确定result的类型
        if (oClass === "Object") {
            result = {};
        } else if (oClass === "Array") {
            result = [];
        } else {
            return obj;
        }
        for (key in obj) {
            var copy = obj[key];
            if (isClass(copy) == "Object") {
                result[key] = arguments.callee(copy);//递归调用
            } else if (isClass(copy) == "Array") {
                result[key] = arguments.callee(copy);
            } else {
                result[key] = obj[key];
            }
        }
        return result;
    }

    //初始化下拉框的值
    function initSelecct(el, sql, data) {
        $P.initDropdown($('#' + el), {sql: sql}, {
                idField: 'id',
                keyField: 'word',
                effectiveFields: ['word'],
                defaultValue: myParams[el]
            }
            , function (datas, e) {
                myParams[el] = datas["id"]
            }, '../../../../api/baseCommonqueryController/getSelectOption');
    }

    //初始化日期控件
    function initDate(el, field) {
        //初始化日期输入框
        laydate({
            elem: '#' + el,
            choose:function (datas) {
                myParams[field] = datas;
            }
        });
    }

//返回传递给他的任意对象的类
    function isClass(o) {
        if (o === null) return "Null";
        if (o === undefined) return "Undefined";
        return Object.prototype.toString.call(o).slice(8, -1);
    }
});
